package net.xdclass.order.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @DESCRIPTION feign的请求拦截器，用于将用户请求头设置给feign代理后的请求，防止代理后丢失请求头
 * @Author yaya
 * @DATE 2022/10/7
 */
@Slf4j
@Configuration
public class FeignInterceptor {


    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        return requestTemplate -> {
            // 通过RequestContextHolder拿到用户的request
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if(requestAttributes != null){
                // 通过RequestContextHolder拿到用户的request
                HttpServletRequest request = requestAttributes.getRequest();
                String token = request.getHeader("token");
                // 将用户的cookie设置给feign代理后的请求
                requestTemplate.header("token", token);
            }else {
                log.warn("requestInterceptor获取Header空指针异常");
            }
        };
    }
}